import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
//引用拦截器文件
import { InterceptorService } from "../../../../share/interceptor.service";
//弹出框
import { ConfirmDialogModule, ConfirmationService,DialogModule,TabViewModule,DropdownModule} from 'primeng/primeng';
import { NoticeEntity } from '../../../../models/notice-entity';


import { NzMessageService } from 'ng-zorro-antd';
import { forEach } from '@angular/router/src/utils/collection';

import { NoticeBrowseModel } from '../../../../models/NoticeBrowseModel';
import { PeriodPersonModel } from '../../../../models/PeriodPersonModel';
import { PersonalInfoEntity } from '../../../../models/personal-info-entity';
//弹框
import 'ztree';
import { timeInterval } from 'rxjs/operators/timeInterval';

@Component({
  selector: 'app-edit-notice-info',
  templateUrl: './edit-notice-info.component.html',
  // templateUrl: './test.html',

  
  styleUrls: ['./edit-notice-info.component.css']
})
export class EditNoticeInfoComponent implements OnInit {

  constructor(    private router: Router,
    private confirmationService: ConfirmationService,
    private http: InterceptorService,
    // private messageService: MessageService,    //提示信息
    private activeRoute:ActivatedRoute) { }

  id:any;
  ngOnInit() {
    //this.getData();
    this.id=this.activeRoute.snapshot.paramMap.get("id");
    this.getNotices(this.id);
    this.getCategory();
    //this.getPerson();
    this.queryPage(this.id);
    // this.queryPage();
  }

  //获取通知信息
  selectNoticeInfoUrl = "graduate-web/notice/findNoticeNoticeCategoryById/";
  getNotices(id:String) {
    //let userId = '123SdHAYGfnaGYJa68TenWzPm';
    let url = this.selectNoticeInfoUrl + id; //与后端联调
    //let url = this.selectNoticeInfoUrl ;  //模拟数据
    //let url = this.selectCategoryUrl + userId;
    this.http.get(url).subscribe(
      res => {
        if (res.json().code == '0000') {
          this.noticeEntity = res.json().data;
          //alert(res.json().data);
          console.log(res.json().data);
          console.log(this.noticeEntity);
          this.noticeCategoryId=this.noticeEntity.columnId;
          //this.noticeCategoryName=this.noticeEntity.columnName;
          this.notifyInfo=this.noticeEntity.noticeContent;
          this.notifyTitle=this.noticeEntity.title;
          this.noticeCategory=this.noticeEntity.columnName;
          //alert(this.noticeEntity.title);
        }
      }
    );
  }

  noticeEntity: NoticeEntity=new NoticeEntity();//通知实体
  notices = new Array();



//获取通知分类信息
noticeCategory:any;  //通知类别
noticeCategoryId:any; //选择的通知类型Id
noticeCategoryNames:any[]=[];//通知类型选项
noticeCategoryName:any;//通知类型选项
notifyInfo:any;//通知内容
notifyTitle:any;//通知标题

//获取通知分类信息---显示
getCategory(){
  let url="graduate-web/noticeCategory/selectNoticeCategoryInfo/";
  this.http.get(url).subscribe(res=>{
    if(res ==undefined){
      console.log("查询通知分类无返回结果")
    }else{
      if(res.json().code=='0000'){
        this.noticeCategoryNames = res.json().data;
        console.log(this.noticeCategoryNames)
      }else{
        console.log(res.json().message)
      }
    }
  })

}

zNodes:any[];
setting = {
  data: {
    simpleData: {
      enable: true
    }
  },
  check: {
      enable: true
  }
};
personIds:any[]=[];
periodPersonModels:PeriodPersonModel[]=[];
//获取接收人信息
getPerson(){
  let url = 'graduate-web/browse/findPeriodPersonModels/';
  this.http.get(url).subscribe(res=>{
    if(res ==undefined){
      console.log("查询接收人信息无返回结果")
    }else{
      if(res.json().code=='0000'){
        this.periodPersonModels=res.json().data;
        this.setPersonOptions();
      }else{
        console.log(res.json().message);
        this.showDialog(res.json().message+"\n请尝试刷新！");
      }
    }
  })
}

//设置人员树形结构
setPersonOptions(){
  let nodes:any[]=[];
  nodes.push({id:0,name:'全部联系人'});
  this.periodPersonModels.forEach(periodPersonModel=>{
    nodes.push({id:periodPersonModel.periodId,pId:0,name:periodPersonModel.periodName});
    if(periodPersonModel.personalInfoList!=null){
      //接收人员信息
      let personalInfoEntitys:PersonalInfoEntity[]=periodPersonModel.personalInfoList;
      personalInfoEntitys.forEach(person=>{
        nodes.push({id:person.id,pId:periodPersonModel.periodId,name:person.name})
      })
    }
  })
  this.zNodes=nodes;
  //生成属性结构
  $.fn.zTree.init($("#ztree"),this.setting,this.zNodes);
}




/**修改通知信息
 *
 */
editNotice(){

  // 验证数据内容

  //获取分类数据
  console.log(this.noticeCategoryId);
  if(this.noticeCategoryId ==undefined){
    console.log("请选择通知类别");
    this.showDialog("请选择通知类别");
    return;
  }
  this.noticeEntity.columnId=this.noticeCategoryId;

  //获取通知ID
  this.noticeEntity.id=this.id;
  
  //获取接收人数据
  var treeObj =$.fn.zTree.getZTreeObj("ztree");
  var nodes = treeObj.getCheckedNodes();
  let browsePersons:NoticeBrowseModel[]=[];
  for(let i=0;i<nodes.length;i++){
    if (!nodes[i].isParent) {
      let browsePerson:NoticeBrowseModel=new NoticeBrowseModel();
      browsePerson.browsePersonId=nodes[i].id;
      browsePersons.push(browsePerson);
    } 
  }
  if(browsePersons.length==0){
    console.log("请选择接收人");
    this.showDialog("请选择接收人");
    return;
  }
  this.noticeEntity.browsePersons=browsePersons;

  //获取通知标题
  //获取通知内容
  if(this.notifyTitle==undefined){
    console.log("请输入通知标题");
    this.showDialog("请输入通知标题");
    return;
  }
  this.noticeEntity.title = this.notifyTitle;

  //获取通知内容
  if(this.notifyInfo==undefined){
    console.log("请输入通知内容");
    this.showDialog("请输入通知内容");
    return;
  }
  this.noticeEntity.noticeContent=this.notifyInfo;

  //补充其他数据
  this.noticeEntity.operator=localStorage.getItem('userName')==undefined?"大米时代":"大米时代";//操作人名称
  this.noticeEntity.operatorId=localStorage.getItem('userId')==undefined?"bjdmsd":this.noticeEntity.publisherId=localStorage.getItem('userId');//操作人Id
  this.noticeEntity.publisherId=localStorage.getItem('userId')==undefined?"bjdmsd":this.noticeEntity.publisherId=localStorage.getItem('userId');//创建人ID
  
  //提交到服务器
  let url="graduate-web/notice/updateNoticeBrowse/";
  // let url="graduate-web/notice/updateNotice/";
  let body=JSON.stringify(this.noticeEntity);
  this.http.post(url,body).subscribe(res=>{
    if(res ==undefined){
      console.log("查询通知分类无返回结果")
    }else {
      console.log(res.json().message);
      
      this.showDialog(res.json().message);
      //todo 如何延时触发跳转  
      if(res.json().code=='0000'){
        //返回上一页
        // this.router.navigateByUrl('workspace/notice/my-notice');
        this.router.navigateByUrl("workspace/notice/my-notice/notice-info/" + this.id);
      }
    }
  })
}

// //操作完成后，跳转回到该通知页面
// backNotice(){ 
    
//     this.id=this.activeRoute.snapshot.paramMap.get("id");  //获取路由跳转传回的ID，点击取消按钮从页面未传回ID
//     alert("backNotice方法："+this.id);
//     this.router.navigateByUrl("workspace/notice/my-notice/notice-info/" + this.id);
// }

editNoticeFlag=true;
//取消修改
cancelClick(){
  //清除数据
  this.personIds=[];
  this.noticeCategoryId=undefined;
  this.notifyInfo=undefined;
  this.editNoticeFlag=false;
  this.router.navigateByUrl("workspace/notice/my-notice/notice-info/" + this.id);
  
}

//**********************************************提示框Start**************************************88 */
display:boolean=false;
messages:"";
/**
 * 提示框
 */
showDialog(string){
  this.messages=string;
  this.display=true;
}
/**********************************************提示框END**************************************88 */



/**填充页面资源树---全部接收人，并标记已选择的接收人
 * 
 */
queryPage(id:String){
  //设置zTree属性
  let setting = {
    check: {
      enable: true,
      chkStyle: "checkbox",
      chkboxType: { "Y" : "ps", "N" : "ps" }
    },
    data: {
      simpleData: {
        enable: true,
        idKey: "id",
        pIdKey: "pId",
        rootPId: "0"
      }
    }
  };
  let zNodesData;
  // let selectTreeBrowserUrl:any;
  let url = "graduate-web/browse/selectAllBrowserByNoticeIdAsTree/"+id ;  //后端联调
  // let url =  'src/Data-Test/select-tree-browser.json' ;  //模拟数据
  this.http.get(url).subscribe(
    res =>{
      if(res.json().code == "0000"){
        zNodesData = res.json().data;
        let nodes:any[]=[];
        nodes.push({id:0,name:'全部联系人'});
        $.fn.zTree.init($("#ztree"),setting,zNodesData);
      }
      // else{
        // this.msgs=[];          
        // this.msgs.push({severity:'error', summary:'错误', detail:'获取数据失败，请联系管理员！'});
        //alert("question");
      // }
    }
  )
}

/**条件查询-根据条件查询该人是否存在，并标记树形结构
 * 
 */
SearchpersonName=this.SearchpersonName;  //获取搜索的姓名
combinationSearch(id:String) {
  let url = "graduate-web/browse/selectBrowserByCombination/"+this.SearchpersonName+'/' +this.id ;  //后端联调
  //获取查询的姓名
  if(this.SearchpersonName==undefined){
    console.log("请输入查询的姓名");
    this.showDialog("请输入查询的姓名");
    return;
  }

  this.http.get(url).subscribe(
    res => {
      if (res.json().code == "0000") {
        if (res.json().message == "没有查询到此人") {
          console.log(res.json().message);
          this.showDialog("没有查询到此人!");
        } else {
          console.log("**************************重新加载树************************");
          //设置zTree属性
          let setting = {
            check: {
              enable: true,
              chkStyle: "checkbox",
              chkboxType: { "Y" : "ps", "N" : "ps" }
            },
            data: {
              simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: "0"
              }
            }
          };
          let zNodesData=res.json().data;
          let nodes:any[]=[];
          nodes.push({id:0,name:'全部联系人'});
          $.fn.zTree.init($("#ztree"),setting,zNodesData);
        }
      } 
    });
}
}

//定义条件查询接受参数
// export class Condition {
//   SearchpersonName?: String
// }